from pymt import *
import os
import random
from OpenGL.GL import *
import copy
import Image
import MTTouchAndShowButton
import MTTextZone
import MTMediaZone


current_dir = os.path.dirname(__file__)

class MTPageWindow(MTInnerWindow):

    def __init__(self, function, id, **kwargs):
        print "MTPageWindow constructed"
        kwargs.setdefault('scale_min', 0.5)
        kwargs.setdefault('scale_max', 2)
        self.height_max = 480
        self.height_min = 300
        self.width_max = 720
        self.width_min = 400
        self.grow_delta = Vector(0, 0)
        # self.aspect_controls_touches = {}
        self.window_controls_touches = []
        self.text_zones= []
        self.media_zones= []		
        super(MTPageWindow, self).__init__(**kwargs)
		
        # self.add_hold_aspect_ratio_controls()
        self.add_window_controls()
        self.function=function
        self.__id=id 
        self.label=id+1
		
        self.scale_container=False
		
        # animate the appearance of the window
        self.scale_min_old = self.scale_min
        self.scale_min = 0.01
        self.scale = 0.01
        self.show_window_anim = Animation(duration=0.5, scale = 1, f = "ease_out_elastic")
        @self.show_window_anim.event
        def on_complete(self):
            self.scale_min = self.scale_min_old
            print "Show window anim complete"
        self.do(self.show_window_anim)
        self.is_fullscreen = False
        print "Leaving MTPageWindow constructor"
        self.text_label = MTLabel(label=self.label, pos =(self.width/2-20,self.height/2-20), cls="labelPage")
        self.add_widget(self.text_label)

    def close(self, touch):
        self.visible=0
        self.function(id=self.__id)

    def delete(self, touch):
        # stop any videos in this window otherwise they'll keep playing
        
        print "MTPageWindow hack to stop any videos playing when the window is closed"
        self.stop_videos_hack(self.container)

        # animate the closing of the window
        self.width_min = 1
        self.height_min = 1
        self.scale_min = 0.01
        self.closing_anim = Animation(duration=0.2, scale=0.01, f = "ease_in_quad")
        @self.closing_anim.event
        def on_complete(self):
            super(MTPageWindow, self).close(touch)
        self.do(self.closing_anim)


    def stop_videos_hack(self, starting_widget):
        #print "MTPageWindow::stop_videos_hack starting_widget.__class__.__name__ is ", starting_widget.__class__.__name__

        if(starting_widget.__class__.__name__ == "MTVideo"):
            starting_widget.player.stop()
        for content in starting_widget.children:
            self.stop_videos_hack(content)


    def textZone(self, touch):
        print "draw a text zone"
		
        self.width_zone = self.width/4
        self.height_zone = self.height/4
        self.text_zone = MTTextZone.MTTextZone(pos =((self.width/2)-(self.width_zone /2),5), size =(self.width_zone,self.height_zone), parent_height=self.height, parent_width=self.width, do_rotation=0) 
        self.add_widget(self.text_zone)
        
        self.text_zones.append(self.text_zone)

    def mediaZone(self, touch):
        print "draw a text zone"
		
        self.width_zone = self.width/4
        self.height_zone = self.height/4
		
        self.media_zone = MTMediaZone.MTMediaZone(pos =((self.width/2)-(self.width_zone /2),5), size =(self.width_zone,self.height_zone), parent_height=self.height, parent_width=self.width, do_rotation = 0) 
        self.add_widget(self.media_zone)
        
        self.media_zones.append(self.media_zone)

    

    def add_window_controls(self):
        self.window_controls = MTTouchAndShowButton.MTTouchAndShowButton(filename="resources/graphics/aspectControlButtonTextureBottomDots.png", start_angle = 150, end_angle = 210, sub_buttons_radius_extra_spacing = 50)
        #self.window_controls.fixed_scale = 1 # this value is used to fix the scaling of the window controls. MTWidget __slots__
        self.add_widget(self.window_controls) # not sure if this is needed. Works without it.
        #self.window_controls.add_sub_button("resources/graphics/fullscreen.png", self.fullscreen)
        self.window_controls.add_sub_button("resources/graphics/mediaZone.png", self.mediaZone)
        self.window_controls.add_sub_button("resources/graphics/close.png", self.close)
        self.window_controls.add_sub_button("resources/graphics/textZone.png", self.textZone)


    def update_window_controls(self):
        # hack to lock the window controls to stay the same size when the window is resized
        scaled_border = self.get_scaled_border()
        self.window_controls.scale = 1.0 / self.scale # do not scale the window controls
        for child in self.window_controls.children:
            child.scale = 1.0 / self.scale # do not scale the window controls
        self.window_controls.pos = ((self.width / 2) - (self.window_controls.width / 2), (-scaled_border / 2) - (self.window_controls.height / 2))



    def on_touch_down(self, touch):

        # if the touch isn't on the widget we do nothing
        if not self.collide_point(touch.x, touch.y):
            MTInnerWindow.on_touch_down(self, touch)
            return False

        local_touch = self.to_local(touch.x, touch.y)

        if(self.window_controls.collide_point(local_touch[0], local_touch[1])):
            #print "windows controls touched"
            self.window_controls.on_press(local_touch)
            self.window_controls_touches.append(touch.id)
            return True

        # if(len(self.aspect_controls_touches.keys()) == 0): # only one touch allowed at a time on the aspect ratio controls
            # if(self.aspect_control_top_right.collide_point(local_touch[0], local_touch[1])):
                # print "MTPageWindow touch down over top right aspect control"
                # self.aspect_controls_touches[touch.id] = ["top", "right"]

            #else:
                #'print "MTPageWindow touch down NOT over aspect controls"
        # if(self.container.collide_point(local_touch[0], local_touch[1])):
			# self.scale_container=True
        # else:
			# self.scale_container=False
        return MTInnerWindow.on_touch_down(self, touch) # the "return" lets MTInnerWindow deal with the touch
        #return True # don't let this touch get sent to any other widget. This was a mistake as it stops any of this window's children receiving the event.

    # def on_touch_move (self, touch):
		# if not self.collide_point(touch.x, touch.y):
			# MTInnerWindow.on_touch_move(self, touch)
			# return False
		# print len(self.touches), self.scale_container			
		# if self.scale_container==True:
			# print "scale"
			# self.container.scale=0.5
		# return MTInnerWindow.on_touch_move(self, touch)
		

    def on_touch_up(self, touch):
        # if touch in self.aspect_controls_touches then remove it
        # if(touch.id in self.aspect_controls_touches.keys()):
            # del self.aspect_controls_touches[touch.id]

        if(touch.id in self.window_controls_touches):
            local_touch_pos = self.to_local(touch.x, touch.y)
            local_touch = copy.deepcopy(touch)
            local_touch.x = local_touch_pos[0]
            local_touch.y = local_touch_pos[1]
            self.window_controls_touches.remove(touch.id)
            self.window_controls.on_release(local_touch)

        return MTInnerWindow.on_touch_up(self, touch)


    def apply_angle_scale_trans(self, angle, scale, trans, point=Vector(0, 0)):
		# print len(self.touches), self.scale_container
		if(self.scale_container==True):
			print "scale2"
			MTScatterWidget.apply_angle_scale_trans(self, angle, scale, trans, point)
		else:
			scale=0
			MTScatterWidget.apply_angle_scale_trans(self, angle, scale, trans, point)
        # if(len(self.aspect_controls_touches.keys()) >= 1 and len(self.touches) == 1):    # change size rather than scale

            # grow_delta = Vector(trans.x, trans.y)
            # grow_delta = grow_delta.rotate(360.0 - self.rotation)

            # aspect_control_location = self.aspect_controls_touches.items()[0][1]

            # handle switch in direction of growth
            # left
            # if("left" in aspect_control_location):
                # grow_delta[0] *= -1.0
            # bottom
            # if("bottom" in aspect_control_location):
                # grow_delta[1] *= -1.0

            # change the size
            # self.width += grow_delta[0]
            # self.height += grow_delta[1]

            # offset the window
            # trans.x = 0
            # trans.y = 0
            # left
            # if("left" in aspect_control_location):
                # trans.x = -grow_delta[0]
            # bottom
            # if("bottom" in aspect_control_location):
                # trans.y = -grow_delta[1]

            # check that the widget isn't too small or too large
            # if(self.height <= self.height_min):
                # self.height = self.height_min
            # elif(self.height >= self.height_max):
                # self.height = self.height_max
            # if(self.width <= self.width_min):
                # self.width = self.width_min
            # elif(self.width >= self.width_max):
                # self.width = self.width_max

            # resize the widget's container too
            # self.container.height = self.height
            # self.container.width = self.width

            #invalidate cached values for parent transform calucaltion
            #self.__to_local = (-9999, 9999)
            #self.__to_parent = (-9999, 9999)
            #self.dispatch_event('on_transform', angle, scale, trans, point)

            # scale = 0
            # rotate = 0
            
            # self.dispatch_event('on_transform', angle, scale, trans, point)


        #else:
            # apply the changes as normal if not changing the aspect ratio
        # MTScatterWidget.apply_angle_scale_trans(self, angle, scale, trans, point)

    def on_transform(self, angle, scale, trans, point):
        #print "on_transform"
        # self.update_aspect_controls()
        self.update_window_controls()
    
    def _get_id(self):
        return self._id
	
    def _get_media_zones(self):
        return self.media_zones
	media_zones = property(media_zones)
	
    def _get_text_zones(self):
        return self.text_zones
	text_zones = property(text_zones)	

    def draw(self):
        MTInnerWindow.draw(self)
        self.window_controls.dispatch_event('on_draw')
        # self.aspect_controls.dispatch_event('on_draw')

